package cn.blnp.net.flowable.boot.custom.verify;

import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.engine.*;
import org.flowable.engine.impl.cfg.multitenant.MultiSchemaMultiTenantProcessEngineConfiguration;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.TaskQuery;
import org.flowable.validation.ProcessValidator;
import org.flowable.validation.ValidationError;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.util.List;

/**
 * <h3>自定义流程校验案例演示</h3>
 *
 * @author <a href="mailto:blnp.yibin@qq.com">lyb</a>
 * @version 1.0
 * @since 2025/6/9 11:31
 */
@Slf4j
@SpringBootTest
public class CusValidatorTest {

    @Resource
    private RepositoryService repositoryService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private IdentityService identityService;
    @Resource
    private TaskService taskService;
    @Resource
    private ProcessValidator  processValidator;
    @Resource
    private ProcessEngineConfiguration processEngineConfiguration;

    /**
     *  <h2>自定义流程校验案例演示</h2>
     *  <p>
     *      该流程为运维申请流程，这里任务审批节点都没有分配具体的审批人、候选人以及组信息。
     *      <ul>
     *          <li><b>流程定义文件：</b>{@link flow/CustomValidatorProcess.bpmn20.xml}</li>
     *          <li>
     *              <b>流程预览图：</b></br>
     *              <img src="https://cdn4.winhlb.com/2025/06/09/68465c2e00f28.png" >
     *          </li>
     *      </ul>
     *  </p>
     **/
    @Test
    public void test() {
        Deployment deploy = repositoryService.createDeployment()
                .addClasspathResource("flow/CustomValidatorProcess.bpmn20.xml")
                .name("自定义流程校验案例")
                .deploy();
        //流程定义信息
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                .deploymentId(deploy.getId())
                .singleResult();
        log.info("流程定义ID：{}", processDefinition.getId());

        //启动流程实例
        ProcessInstance procInst = runtimeService.startProcessInstanceById(processDefinition.getId());
        log.info("流程实例ID：{}", procInst.getId());
        TaskQuery taskQuery = taskService.createTaskQuery()
                .processInstanceId(procInst.getId());
        log.info("待办任务数量：{}", taskQuery.count());
        log.info(" -=== 开始执行模型校验！");
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        //获取自定义流程校验器
        List<ValidationError> validate = processValidator.validate(bpmnModel);
        //如果校验错误集合长度大于1，则说明校验出错，遍历打印出错信息
        if(!validate.isEmpty()){
            for (ValidationError validationError : validate) {
                log.error("{} 校验异常：{}", validationError.getValidatorSetName(), validationError.getProblem());
            }
        }

        /**
         *  演示结果：
         *  2025-06-09 11:54:50.486 ERROR 27112 --- [           main] o.f.e.i.b.d.ParsedDeploymentBuilder      : Could not parse resource flow/CustomValidatorProcess.bpmn20.xml
         *
         * org.flowable.common.engine.api.FlowableException: Errors while parsing:
         * [Validation set: 'custom-validtor' | Problem: '用户任务【财务】 办理人、候选人、候选组不能全为空'] : 用户任务节点办理人、候选人、候选组不能全为空 - [Extra info : processDefinitionId = CustomValidatorProcess | processDefinitionName = 自定义流程校验 |  | id = sid-94992FCF-63BE-4604-8A0D-BA1F7C7A0505 |  | activityName = 财务 | ] ( line: 4, column: 112)
         * [Validation set: 'custom-validtor' | Problem: '用户任务【任务】 办理人、候选人、候选组不能全为空'] : 用户任务节点办理人、候选人、候选组不能全为空 - [Extra info : processDefinitionId = CustomValidatorProcess | processDefinitionName = 自定义流程校验 |  | id = sid-55548CDA-FC8E-4F0C-98FE-1F1269EBC340 |  | activityName = 任务 | ] ( line: 6, column: 112)
         * [Validation set: 'custom-validtor' | Problem: '用户任务【行政】 办理人、候选人、候选组不能全为空'] : 用户任务节点办理人、候选人、候选组不能全为空 - [Extra info : processDefinitionId = CustomValidatorProcess | processDefinitionName = 自定义流程校验 |  | id = sid-9DC84933-62B0-4505-9DAA-475FCCB4530A |  | activityName = 行政 | ] ( line: 8, column: 112)
         *
         * at cn.blnp.net.flowable.boot.custom.verify.CusValidatorTest.test(CusValidatorTest.java:58) ~[test-classes/:na]
         **/
    }
}
